package penguin

import (
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	irisLogger "github.com/kataras/iris/v12/middleware/logger"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"path"
	"runtime"
	"strconv"
	"time"
)

var logger *golog.Logger

func configLog(app *iris.Application) {
	logger = app.Logger()
	var data = struct {
		Debug   bool   `json:"debug"`
		LogFile string `json:"logFile"`
	}{}
	loadConfigJson("config/log.json", &data)
	if !data.Debug {
		appLog(data.LogFile, app)
	} else {
		app.Use(irisLogger.New())
	}
}

func appLog(logFile string, app *iris.Application) {
	writer, err := rotatelogs.New(
		logFile+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(logFile),
		rotatelogs.WithMaxAge(7*24*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour))
	if err != nil {
		panic(err)
	}
	app.Logger().SetOutput(writer)
}

func Error(arg ...interface{}) {
	_, file, line, ok := runtime.Caller(1)
	if !ok {
		file = "???"
		line = 0
	}
	_, filename := path.Split(file)
	msg := "[" + filename + ":" + strconv.Itoa(line) + "] "
	logger.Error(msg, arg)
}
